import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get_state_manager/get_state_manager.dart';
import 'package:m6/Untils/api.dart';
import 'package:m6/Untils/request.dart';
import 'package:m6/Untils/toast.dart';
import 'package:get/get.dart';
import 'package:m6/business/home/model/product_model.dart';
import 'package:m6/business/home/page/product_detail.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  HomeController dataCont = Get.put(HomeController());
  ScrollController scrolCon = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          decoration: const BoxDecoration(color: Color(0xFFF0EDEC)),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: [topImage(), productsList()],
          )),
    );
  }

  Widget topImage() {
    return Container(
      decoration: const BoxDecoration(color: Color(0xFF3154E2)),
      padding:
          EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
      height: MediaQueryData.fromWindow(window).padding.top + 180,
      child: Image.asset(
        "recource/images/home_banner.png",
        width: MediaQuery.of(context).size.width,
        height: 180,
        fit: BoxFit.fill,
      ),
    );
  }

  Widget productsList() {
    return Expanded(
        child: MediaQuery.removeViewPadding(
            removeTop: true,
            removeLeft: true,
            removeRight: true,
            context: context,
            child: EasyRefresh(
              onRefresh: () async {
                dataCont.refreshData();
              },
              onLoad: Get.find<HomeController>().hasMore.value == false
                  ? null
                  : () async {
                      dataCont.loadMoreData();
                    },
              child: GetBuilder<HomeController>(builder: (e) {
                return ListView.builder(
                    shrinkWrap: true, //解决 ListView 高度超标问题
                    controller: scrolCon,
                    itemCount: e.products.length,
                    itemBuilder: (BuildContext context, index) {
                      return productCard(e.products[index]);
                    });
              }),
            )));
  }

  List<Widget> productsWidget() {
    List<Widget> a = [];
    for (var m in dataCont.products) {
      a.add(productCard(m));
    }
    return a;
  }

  Widget productCard(ProductModel product) {
    return Card(
      shadowColor: Colors.white,
      margin: const EdgeInsets.only(left: 10, right: 10, top: 10),
      color: Colors.white,
      child: Container(
        height: 170,
        child: Column(
          children: [
            Row(
              children: [
                Expanded(
                  child: Container(
                    padding: const EdgeInsets.only(left: 15, top: 15),
                    // decoration: BoxDecoration(color: Colors.red),
                    child: Row(
                      children: [
                        Image.network(
                          product.productLogoUrl,
                          width: 24,
                          height: 24,
                        ),
                        Container(
                          width: 4,
                        ),
                        Text(product.productName),
                        Container(
                          margin: const EdgeInsets.only(left: 8, right: 8),
                          padding: const EdgeInsets.all(4),
                          height: 18,
                          decoration: const BoxDecoration(
                              color: Color(0xFFF0EDEC),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(2))),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text(
                                product.score,
                                style: TextStyle(fontSize: 10),
                              ),
                              Icon(
                                Icons.star,
                                color: Colors.yellow,
                                size: 14,
                              )
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ),
                Container(
                  height: 40,
                  padding: EdgeInsets.zero,
                  // decoration: BoxDecoration(color: Colors.green),
                  child: SizedBox(
                    width: 30,
                    child: Image.asset(
                      "recource/images/home_icon_vip.png",
                      fit: BoxFit.cover,
                    ),
                  ),
                )
              ],
            ),
            Container(
              margin: EdgeInsets.only(top: 16, left: 16, right: 16),
              // width: 120,
              height: 1,
              decoration: BoxDecoration(color: Color(0xFFEEEEEE)),
            ),
            Container(
              padding: EdgeInsets.only(right: 16),
              // decoration: BoxDecoration(color: Colors.green),
              // margin: EdgeInsets.only(top: 37.5),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(left: 30, top: 14),
                      // decoration: BoxDecoration(color: Colors.red),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            "\$${product.maxAmount}",
                            style: TextStyle(
                                color: Colors.black,
                                fontSize: 34,
                                fontWeight: FontWeight.w500),
                          ),
                          Text(
                            "Préstamo máximo",
                            style: TextStyle(
                                color: Color(0xFF666666), fontSize: 14),
                          ),
                          Container(
                            height: 8,
                          ),
                          Text(
                            "Interés diario≥${product.interestRate}%",
                            style: TextStyle(
                                color: Color(0xFF333333), fontSize: 14),
                          ),
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 34,
                    child: ElevatedButton(
                        style: const ButtonStyle(
                            backgroundColor: MaterialStatePropertyAll<Color>(
                                Color(0xFF3154E2))),
                        onPressed: () {
                          Get.to(() => const ProductDetail());
                        },
                        child: Text(
                          applyButtonText(product.userStatus),
                          // "Solicitar inmediatamente",
                          maxLines: 2,
                          style: TextStyle(fontSize: 10, color: Colors.white),
                        )),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  String applyButtonText(int statu) {
    switch (statu) {
      case 2:
        return "Under Review";
      case 4:
        return "Solicitud no aprobada";
      case 5:
        return "Solicitar de nuevo";
      case 3:
      case 6:
        return "Audit approved";
      case 7:
        return "To Payment";
      case 8:
        return "Overdue";
    }
    return "Solicitar inmediatamente";
  }
}

class HomeController extends GetxController {
  List<ProductModel> products = [];
  var page = 1;

  var hasMore = true.obs;

  @override
  void onInit() {
    getProducts();
    super.onInit();
  }

  void refreshData() {
    page = 1;
    hasMore.value = true;
    products = [];
    getProducts();
  }

  void loadMoreData() {
    if (hasMore.value == false) {
      return;
    }
    page++;
    getProducts();
  }

  Future<void> getProducts() async {
    MToast.ShowLoading(null);
    CustomerResponse response = await Request.get(
        URL_Home_Products,
        {"pageNumber": page, "pageSize": 10}
            .map((key, value) => MapEntry(key, value.toString())));
    MToast.HiddenLoading();
    if (response.code == 1) {
      int total = response.data?["total"];
      List<dynamic> recommendItems = response.data?["recommendItems"];
      // products = recommendItems
      //     .map((e) => ProductModel.fromJson(e))
      //     .cast<Type>()
      //     .toList();
      for (Map<String, dynamic> e in recommendItems) {
        final a = ProductModel.fromJson(e);
        products.add(a);
      }
      if (products.length == total) {
        hasMore.value = false;
      } else {
        hasMore.value = true;
      }
      update();
    } else {
      MToast.ShowMessage(response.msg);
    }
  }
}
